// import axios from 'axios'
import{ List, Badge } from 'antd-mobile'
import React from 'react'
import { connect } from 'react-redux'
import withRouter from '../withRouter'
@withRouter
@connect(
    state=>state
)
class Msg extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            data: []
        }
    }
    componentDidUpdate() {
    }
    getLast(arr) {
        return arr[arr.length-1]
    }
    render(h) {
        // console.warn(this.props)
        // if(!this.props.chat.chatmsg.length) return []
        const msgGroup = {}
        const Item = List.Item
        const Brief = Item.Brief
        const userid = this.props.user._id
        const userinfo = this.props.chat.users
        this.props.chat.chatmsg.forEach(v => {
            // msgGroup[v.chatid] = msgGroup[v.chatid] || []
            // msgGroup[v.chatid].push(v)
            msgGroup[v.chatid] && msgGroup[v.chatid].push(v) || (msgGroup[v.chatid] = [])
        })
        const chatList = Object.values(msgGroup).sort((a,b)=> {
            if(this.getLast(a)) {
                const a_last = this.getLast(a).create_time
                const b_last = this.getLast(b).create_time
                return b_last - a_last
            }
        })
        // const chatIds = Object.keys(msgGroup)
        // console.log(msgGroup, chatList)
        // 按照聊天用户分组，根据chatid
        return (
            <div>
                {chatList.map((msglist, i) => {
                    // msglist.sort((a,b)=> b.create_time - a.create_time)
                    // const lastItem = msglist.slice(-1)[0]
                    if(msglist.length) {
                        const lastItem = this.getLast(msglist)
                        const targetId = lastItem.from === userid?lastItem.to:lastItem.from
                        const unreadNum = msglist.filter(v => !v.read && v.to===userid).length
                        const name = userinfo[targetId]?.name || ''
                        const avatar = userinfo[targetId]?.avatar || ''
                        return <List key={lastItem._id}>
                                <Item extra={<Badge text={unreadNum}></Badge>}
                                    thumb={require(`../img/${avatar}.png`)}
                                    arrow='horizontal'
                                    onClick={v => {
                                        this.props.navigate(`/chat/${targetId}`)
                                    }}
                                    >
                                    {lastItem.content}
                                    <Brief>{name}</Brief>
                                </Item>
                            </List>
                    }
                })}
            </div>
        )
    }
}

export default Msg